package com.spr.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spr.mapper.SprDeviceCameraInfoMapper;
import com.spr.mapper.SprDevicePartInfoMapper;
import com.spr.mapper.SprSiteInfoMapper;
import com.spr.mapper.SprWorkshopDeviceInfoMapper;
import com.spr.pojo.SprDeviceCameraInfo;
import com.spr.pojo.SprSiteInfo;
import com.spr.pojo.SprWorkshopDeviceInfo;
import com.spr.service.SprDeviceImportService;
import com.spr.vo.excel.SprSiteInfoExcelVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class SprDeviceImportServiceImpl  implements SprDeviceImportService {

    private static final Logger log = LoggerFactory.getLogger(SprDeviceImportServiceImpl.class);
    @Autowired
    private SprSiteInfoMapper sprSiteInfoMapper;
    @Autowired
    private SprDeviceCameraInfoMapper sprDeviceCameraInfoMapper;
    @Autowired
    private SprDevicePartInfoMapper sprDevicePartInfoMapper;
    @Autowired
    private SprWorkshopDeviceInfoMapper sprWorkshopDeviceInfoMapper;


    @Transactional
    @Override
    public ResponseEntity excelImportPreviousPerformance(MultipartFile file) {
        // 读取Excel数据
        try {
            List<SprSiteInfoExcelVO> excelDtos = EasyExcel.read(file.getInputStream())
                    .head(SprSiteInfoExcelVO.class)
                    .sheet()
                    .doReadSync();

            if (CollectionUtils.isEmpty(excelDtos)) {
                log.warn("导入失败，数据为空");
                return ResponseEntity.ok("导入失败，数据为空");
            }

            log.info("开始导入数据，共{}条记录", excelDtos.size());

            for (int i = 0; i < excelDtos.size(); i++) {
                SprSiteInfoExcelVO excelDto = excelDtos.get(i);
                try {
                    processSingleRecord(excelDto);
                    log.debug("成功处理第{}条记录，站点名称: {}", i + 1, excelDto.getSiteName());
                } catch (Exception e) {
                    log.error("处理第{}条记录时发生错误，站点名称: {}，错误信息: {}",
                            i + 1, excelDto.getSiteName(), e.getMessage(), e);
                    // 继续处理下一条记录而不是中断整个导入过程
                }
            }

            log.info("数据导入完成");
            return ResponseEntity.ok("导入成功");

        } catch (IOException e) {
            log.error("读取Excel文件失败", e);
            throw new RuntimeException("文件读取失败: " + e.getMessage(), e);
        } catch (Exception e) {
            log.error("导入过程中发生未知错误", e);
            throw new RuntimeException("导入失败: " + e.getMessage(), e);
        }
    }

    /**
     * 处理单条记录
     * @param excelDto Excel数据对象
     */
    private void processSingleRecord(SprSiteInfoExcelVO excelDto) {
        // 提取数据
        String workshopName = excelDto.getWorkshopName();
        String deviceStatus = excelDto.getDeviceStatus();
        String deviceName = excelDto.getDeviceName();
        String deviceNumber = excelDto.getDeviceNumber();
        String siteName = excelDto.getSiteName();
        String siteAddress = excelDto.getSiteAddress();
        String siteLatitudeLongitude = excelDto.getSiteLatitudeLongitude();
        String siteStatus = excelDto.getSiteStatus();
        String cameraUrlString = excelDto.getCameraUrlString();

        List<SprWorkshopDeviceInfo> sprWorkshopDeviceInfos = sprWorkshopDeviceInfoMapper.selectList(new LambdaQueryWrapper<SprWorkshopDeviceInfo>()
                .eq(SprWorkshopDeviceInfo::getWorkshopName, workshopName)
                .eq(SprWorkshopDeviceInfo::getDeviceNumber, deviceNumber)
        );
        if (CollectionUtils.isNotEmpty(sprWorkshopDeviceInfos)){
            throw new RuntimeException("已导入车间"+workshopName+",设备号"+deviceNumber+",请勿重复导入");
        }


        // 站点信息
        SprSiteInfo sprSiteInfo = new SprSiteInfo();

        // 处理经纬度
        processLatitudeAndLongitude(siteLatitudeLongitude, sprSiteInfo);

        sprSiteInfo.setSiteAddress(siteAddress);
        sprSiteInfo.setSiteName(siteName);
        sprSiteInfo.setSiteStatus(siteStatus);
        sprSiteInfo.setCreateBy("system");
        sprSiteInfo.setCreateTime(new Date());
        sprSiteInfo.setUpdateBy("system");
        sprSiteInfo.setUpdateTime(new Date());

        sprSiteInfoMapper.insert(sprSiteInfo);

        // 更新siteId字段
        sprSiteInfo.setSiteId(String.valueOf(sprSiteInfo.getId()));
        sprSiteInfoMapper.update(null, new LambdaUpdateWrapper<SprSiteInfo>()
                .set(SprSiteInfo::getSiteId, sprSiteInfo.getId())
                .eq(SprSiteInfo::getId, sprSiteInfo.getId()));

        // 处理设备信息
        SprWorkshopDeviceInfo sprWorkshopDeviceInfo = processWorkshopDevice(
                workshopName, deviceStatus, deviceName, deviceNumber, sprSiteInfo);

        // 处理摄像头信息
        if (cameraUrlString != null && !cameraUrlString.isEmpty()) {
            processCameraInfo(cameraUrlString, sprWorkshopDeviceInfo);
        }
    }

    /**
     * 处理经纬度信息
     * @param siteLatitudeLongitude 经纬度字符串
     * @param sprSiteInfo 站点信息对象
     */
    private void processLatitudeAndLongitude(String siteLatitudeLongitude, SprSiteInfo sprSiteInfo) {
        if (siteLatitudeLongitude != null && siteLatitudeLongitude.contains(",")) {
            try {
                String[] parts = siteLatitudeLongitude.split(",");
                if (parts.length >= 2) {
                    String latitude = parts[0].trim().replace("[", "");
                    String longitude = parts[1].trim().replace("]", "");

                    sprSiteInfo.setLatitude(new BigDecimal(latitude));
                    sprSiteInfo.setLongitude(new BigDecimal(longitude));
                    log.debug("成功解析经纬度: 纬度={}, 经度={}", latitude, longitude);
                } else {
                    log.warn("经纬度格式不正确: {}", siteLatitudeLongitude);
                    sprSiteInfo.setLatitude(null);
                    sprSiteInfo.setLongitude(null);
                }
            } catch (NumberFormatException e) {
                log.warn("经纬度数值格式错误: {}", siteLatitudeLongitude);
                sprSiteInfo.setLatitude(null);
                sprSiteInfo.setLongitude(null);
            }
        } else {
            log.warn("经纬度信息为空或格式不正确: {}", siteLatitudeLongitude);
            sprSiteInfo.setLatitude(null);
            sprSiteInfo.setLongitude(null);
        }
    }

    /**
     * 处理车间设备信息
     * @param workshopName 车间名称
     * @param deviceStatus 设备状态
     * @param deviceName 设备名称
     * @param deviceNumber 设备编号
     * @param sprSiteInfo 站点信息
     * @return 车间设备信息对象
     */
    private SprWorkshopDeviceInfo processWorkshopDevice(String workshopName, String deviceStatus,
                                                        String deviceName, String deviceNumber, SprSiteInfo sprSiteInfo) {

        SprWorkshopDeviceInfo sprWorkshopDeviceInfo = new SprWorkshopDeviceInfo();
        sprWorkshopDeviceInfo.setSiteId(sprSiteInfo.getSiteId());
        sprWorkshopDeviceInfo.setWorkshopName(workshopName);
        sprWorkshopDeviceInfo.setDeviceNumber(deviceNumber);
        sprWorkshopDeviceInfo.setDeviceName(deviceName);
        sprWorkshopDeviceInfo.setTotalSprayParts(null);
        sprWorkshopDeviceInfo.setDistinctPartsCount(null);
        sprWorkshopDeviceInfo.setRunningDays(null);
        sprWorkshopDeviceInfo.setTotalFee(null);
        sprWorkshopDeviceInfo.setDeviceStatus(deviceStatus);
        sprWorkshopDeviceInfo.setCreateBy("system");
        sprWorkshopDeviceInfo.setCreateTime(new Date());
        sprWorkshopDeviceInfo.setUpdateBy("system");
        sprWorkshopDeviceInfo.setUpdateTime(new Date());

        sprWorkshopDeviceInfoMapper.insert(sprWorkshopDeviceInfo);

        // 更新workshopId字段
        sprWorkshopDeviceInfo.setWorkshopId(String.valueOf(sprWorkshopDeviceInfo.getId()));
        sprWorkshopDeviceInfoMapper.update(null, new LambdaUpdateWrapper<SprWorkshopDeviceInfo>()
                .set(SprWorkshopDeviceInfo::getWorkshopId, sprWorkshopDeviceInfo.getId())
                .eq(SprWorkshopDeviceInfo::getId, sprWorkshopDeviceInfo.getId()));

        return sprWorkshopDeviceInfo;
    }

    /**
     * 处理摄像头信息
     * @param cameraUrlString 摄像头URL字符串
     * @param sprWorkshopDeviceInfo 车间设备信息
     */
    private void processCameraInfo(String cameraUrlString, SprWorkshopDeviceInfo sprWorkshopDeviceInfo) {
        try {
            List<String> cameraUrls = JSONArray.parseArray(cameraUrlString).toJavaList(String.class);
            log.debug("处理摄像头信息，共{}个摄像头", cameraUrls.size());

            for (int i = 0; i < cameraUrls.size(); i++) {
                String cameraUrl = cameraUrls.get(i);
                SprDeviceCameraInfo sprDeviceCameraInfo = new SprDeviceCameraInfo();
                sprDeviceCameraInfo.setWorkshopId(sprWorkshopDeviceInfo.getWorkshopId());
                sprDeviceCameraInfo.setCameraNumber(null);
                sprDeviceCameraInfo.setCameraName(null);
                sprDeviceCameraInfo.setCamaraStatus("正常");
                sprDeviceCameraInfo.setCameraUrl(cameraUrl);
                sprDeviceCameraInfo.setCreateBy("system");
                sprDeviceCameraInfo.setCreateTime(new Date());
                sprDeviceCameraInfo.setUpdateBy("system");
                sprDeviceCameraInfo.setUpdateTime(new Date());

                sprDeviceCameraInfoMapper.insert(sprDeviceCameraInfo);
                log.debug("插入第{}个摄像头信息，URL: {}", i + 1, cameraUrl);
            }
        } catch (Exception e) {
            log.warn("处理摄像头信息失败，cameraUrlString: {}", cameraUrlString, e);
        }
    }

}
